define(['jquery.ui', 'template', 'swiper'], function (Ui, Template, Swiper) {

    Template.helper('count', function (data) {
        if (data instanceof Array) {
            return data.length;
        }
        return Object.getOwnPropertyNames(data).length;
    });

    Template.helper('arrayChunk', function (arr, n) {
        if (arr instanceof Array) {
            var newArr = arr;
        } else {
            var newArr = Object.getOwnPropertyNames(arr);
        }

        for (var i = 0, temp = [], l = newArr.length / n; temp.length < l; temp[i++] = newArr.splice(0, n)) ;

        if (typeof arr == 'object') {
            console.log(temp);
            var objectArr = [];
            for (var i = 0; i < temp.length; i++) {
                objectArr[i] = [];
                for (var j = 0; j < temp[i].length; j++) {
                    objectArr[i].push(arr[temp[i][j]]);
                }
            }
            console.log(objectArr);
            return objectArr;
        } else {
            return temp;
        }
    });

    var Pageeditor = {
        data: {
            page: {
                name: '未命名页面',
                title: '请输入页面标题',
                keyword: '',
                desc: '',
                img: '',
                background: '#f3f3f3',
            },
            navs: {
                title: {
                    name: '标题栏',
                    params: {
                        title: '',
                        icon: ''
                    },
                    style: {
                        background: '#ffffff',
                        color: '#666666',
                        textAlign: 'left',
                        fontSize: '12',
                        paddingTop: '5',
                        paddingLeft: '5',
                    }
                },
                blank: {
                    name: '辅助空白',
                    params: {},
                    style: {
                        height: '20',
                        background: '#ffffff'
                    }
                },
                search: {
                    name: '搜索框',
                    params: {
                        placeholder: '请输入关键字进行搜索'
                    },
                    style: {
                        inputBackground: '#ffffff',
                        background: '#f1f1f2',
                        iconColor: '#b4b4b4',
                        color: '#999999',
                        paddingTop: '10',
                        paddingLeft: '10',
                        textAlign: 'left',
                        searchStyle: ''
                    }
                },
                line: {
                    name: '辅助线',
                    params: {},
                    style: {
                        height: '2',
                        background: '#ffffff',
                        border: "#000000",
                        padding: '10',
                        lineStyle: 'solid'
                    }
                },
                banner: {
                    name: '图片轮播',
                    params: {},
                    style: {
                        dotStyle: 'round',
                        dotAlign: 'left',
                        background: '#ffffff',
                        leftRight: '5',
                        bottom: '5',
                        opacity: '0.8'
                    },
                    data: {
                        C0123456789101: {
                            imgUrl: './assets/img/banner-1.jpg',
                            linkUrl: '',
                        },
                        C0123456789102: {
                            imgUrl: './assets/img/banner-2.jpg',
                            linkUrl: '',
                        }
                    }
                },
                picturew: {
                    name: '图片橱窗',
                    params: {column: '4', showtype: 0, rownum: '1'},
                    style: {
                        paddingtop: '0',
                        paddingleft: '0',
                        showbtn: 0,
                        dotStyle: 'round',
                        dotAlign: 'left',
                        background: '#ffffff',
                        leftRight: '5',
                        bottom: '5',
                        opacity: '0.8'
                    },
                    data: {
                        C0123456789101: {
                            imgurl: './assets/img/cube-1.jpg',
                            linkurl: '',
                        },
                        C0123456789102: {
                            imgurl: './assets/img/cube-2.jpg',
                            linkurl: '',
                        },
                        C0123456789103: {
                            imgurl: './assets/img/cube-3.jpg',
                            linkurl: '',
                        },
                        C0123456789104: {
                            imgurl: './assets/img/cube-4.jpg',
                            linkurl: '',
                        }
                    }
                },
                picgroup: {
                    name: '单图组',
                    params: {row: '1', showtype: 0, pagenum: '1'},
                    style: {paddingtop: '0', paddingleft: '0'},
                    data: {
                        C0123456789103: {
                            imgurl: './assets/img/cube-1.jpg',
                            linkurl: '',
                        },
                        C0123456789104: {
                            imgurl: './assets/img/cube-2.jpg',
                            linkurl: '',
                        },
                    }
                },


            },
            items: {},
            selected: '',
        },
        api: {
            // 更新数据
            updateData: function (data, keys, value) {
                keys = keys.split('.');
                if (keys.length > 0) {
                    key = keys.shift();
                    if (keys.length > 0) {
                        data[key] = this.updateData(data[key], keys.join('.'), value);
                    } else {
                        data[key] = value;
                    }
                }
                return data;
            },

            // 获取工具栏
            getToolsNavs: function (ids) {
                var navs = [];
                $.each(ids, function () {
                    var nav = Pageeditor.data.navs[this];
                    nav.id = this.toString();
                    navs.push(nav);
                });
                return navs;
            },

            // 创建元素ID
            createItemID: function (S, N) {
                var date = +new Date();
                var id = S + (date + N);
                return id;
            },

            // 获取最近的元素ID
            getNearItemID: function (itemid) {
                var newarr = [];
                var index = 0;
                var prev = 0;
                var next = 0;
                $.each(Pageeditor.data.items, function (id, obj) {
                    newarr[index] = id;
                    if (id == itemid) {
                        prev = index - 1;
                        next = index + 1;
                    }
                    index++
                });
                var pervid = newarr[prev];
                var nextid = newarr[next];
                if (nextid) {
                    return nextid;
                }
                if (pervid) {
                    return pervid;
                }
                return false
            },

            // 获取数据
            getData: function () {
                return {
                    page: Pageeditor.data.page,
                    items: Pageeditor.data.items,
                };
            },

            init: function (config) {
                $.extend(true, Pageeditor.data.page, config.data.page);
                $.extend(true, Pageeditor.data.items, config.data.items);
                Pageeditor.api.render.page();
                Pageeditor.api.render.tools(config.tools);
                Pageeditor.api.render.propertyTab();
                Pageeditor.api.render.items();
                $("#phone").disableSelection();


            },

            bindevent: function () {
                $(document).on('click', '#page', Pageeditor.api.events.page.onClick);
                $(document).on('click', "#navs nav", Pageeditor.api.events.toolsNavs.onClick);
                $(document).on('input propertychange click', "#diy-editor .diy-bind", Pageeditor.api.events.propertyTab.onChange);
                $(document).on('mousedown click drag.select', '#phone .drag', Pageeditor.api.events.item.onSelect);
                $(document).on('click', '#phone .drag .btn-edit-del .btn-del', Pageeditor.api.events.item.onDel);
                $(document).on('click', '#diy-editor .form-items .btn-add', Pageeditor.api.events.propertyTab.onAdd);
                $(document).on('click', '#diy-editor .form-items .btn-del', Pageeditor.api.events.propertyTab.onDel);
            },

            events: {
                // 页面事件
                page: {
                    // 点击事件
                    onClick: function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        Pageeditor.data.selected = 'page';
                        Pageeditor.api.render.propertyTab();
                        Pageeditor.api.render.items();
                    }
                },
                // 工具栏事件
                toolsNavs: {
                    // 点击事件
                    onClick: function (e) {
                        e.stopPropagation();
                        e.preventDefault();

                        var id = $(this).data('id');

                        var item = $.extend(true, {}, Pageeditor.data.navs[id]);
                        if (!item) {
                            tip.alert("未找到此元素！");
                            return;
                        }
                        if ($("#tpl_show_" + id).length == 0 || $("#tpl_edit_" + id).length == 0) {
                            tip.alert("添加失败！模板错误，请刷新页面重试");
                            return;
                        }

                        var itemid = Pageeditor.api.createItemID("M", 0);

                        if (item.data) {
                            var itemData = $.extend(true, {}, item.data);
                            var newData = {};
                            var index = 0;
                            $.each(itemData, function (id, data) {
                                var childid = Pageeditor.api.createItemID("C", index);
                                newData[childid] = data;
                                delete childid;
                                index++
                            });
                            item.data = newData
                        }

                        Pageeditor.data.items[itemid] = item;
                        Pageeditor.api.render.items();
                        $(document).find(".drag[data-itemid='" + itemid + "']").trigger('mousedown');
                    },
                },
                // 属性选项卡事件
                propertyTab: {
                    // 更改事件
                    onChange: function (e) {
                        var $this = $(this);
                        var itemid = Pageeditor.data.selected;

                        var value = '';
                        var tag = this.tagName;
                        if (tag == 'INPUT') {
                            var type = $this.attr('type');
                            if (type == 'checkbox') {
                                value = [];
                                $this.closest('.form-group').find('input[type=checkbox]').each(function () {
                                    var checked = this.checked;
                                    var valname = $(this).val();
                                    if (checked) {
                                        value.push(valname);
                                    }
                                })
                            } else {
                                var placeholder = $this.data('placeholder');
                                value = $this.val();
                                value = value == '' ? placeholder : value
                            }
                        } else if (tag == 'SELECT') {
                            value = $this.find('option:selected').val();
                        } else if (tag == 'TEXTAREA') {
                            value = $this.val();
                        }
                        value = $.trim(value);
                        if (itemid == 'page') {
                            Pageeditor.api.updateData(Pageeditor.data.page, $this.data("bind"), value);
                            Pageeditor.api.render.page();
                            Pageeditor.api.render.items();
                        } else {
                            Pageeditor.api.updateData(Pageeditor.data.items[itemid], $this.data("bind"), value);
                            if ($(this).attr('type') != 'color') {
                                Pageeditor.api.render.page();
                            }
                            Pageeditor.api.render.items();
                            $(document).find(".drag[data-itemid='" + itemid + "']").trigger('drag.select');
                        }
                    },
                    // 添加元素
                    onAdd: function (e) {
                        e.stopPropagation();
                        e.preventDefault();

                        var itemid = Pageeditor.data.selected;
                        var type = Pageeditor.data.items[itemid].id;
                        var temp = Pageeditor.data.navs[type].data;
                        var max = $(this).closest(".form-items").data('max');
                        if (max) {
                            var length = Object.getOwnPropertyNames(Pageeditor.data.items[itemid].data).length;
                            if (length >= max) {
                                tip.alert("最大添加 " + max + " 个！");
                                return;
                            }
                        }
                        var newChild = {};
                        var index = 0;
                        $.each(temp, function (i, t) {
                            if (index == 0) {
                                newChild = t;
                                index++
                            }
                        });
                        if (newChild) {
                            var childName = Pageeditor.api.createItemID("M", 0);
                            if (typeof(Pageeditor.data.items[itemid].data) === 'undefined') {
                                Pageeditor.data.items[itemid].data = {}
                            }
                            newChild = $.extend(true, {}, newChild);
                            Pageeditor.data.items[itemid].data[childName] = newChild
                        }
                        Pageeditor.api.render.propertyTab();
                        Pageeditor.api.render.items();
                        $(document).find(".drag[data-itemid='" + itemid + "']").trigger('drag.select');
                    },
                    // 删除元素
                    onDel: function (e) {
                        e.stopPropagation();
                        e.preventDefault();

                        var childid = $(this).closest(".item").data('id');
                        var itemid = Pageeditor.data.selected;
                        var min = $(this).closest(".form-items").data("min");
                        if (min) {
                            var length = Object.getOwnPropertyNames(Pageeditor.data.items[itemid].data).length;
                            if (length <= min) {
                                tip.alert("至少保留 " + min + " 个！");
                                return;
                            }
                        }
                        tip.confirm("确定删除吗", function () {
                            delete Pageeditor.data.items[itemid].data[childid];
                            Pageeditor.api.render.propertyTab();
                            Pageeditor.api.render.items();
                            $(document).find(".drag[data-itemid='" + itemid + "']").trigger('drag.select');
                        });
                    },
                },
                // 元素事件
                item: {
                    // 删除事件
                    onDel: function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        var drag = $(this).closest(".drag");
                        var itemid = drag.data('itemid');
                        tip.confirm("确定删除吗？", function () {
                            var nearid = Pageeditor.api.getNearItemID(itemid);
                            delete Pageeditor.data.items[itemid];
                            Pageeditor.api.render.items();
                            if (nearid) {
                                $(document).find(".drag[data-itemid='" + nearid + "']").trigger('mousedown');
                            } else {
                                $("#page").trigger('click');
                            }
                        })
                    },
                    // 选中事件
                    onSelect: function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        // 添加元素选中状态
                        $('#phone .selected').removeClass('selected');
                        $(this).addClass('selected');
                        // 添加元素属性选项卡
                        if (Pageeditor.data.selected != $(this).data('itemid')) {
                            Pageeditor.data.selected = $(this).data('itemid');
                            Pageeditor.api.render.propertyTab();
                        }
                    },
                },
            },

            // 渲染
            render: {
                // 渲染页面
                page: function (page) {
                    $('#pageeditor-page').html(Template('tpl_pageeditor_page', Pageeditor.data.page));
                    Pageeditor.data.selected = 'page';
                },

                // 渲染工具栏
                tools: function (tools) {
                    if (!tools) {
                        return;
                    }

                    var data = {
                        tools: [],
                    };

                    $.each(tools, function () {
                        var navs = Pageeditor.api.getToolsNavs(this.navs.split(','));
                        data.tools.push({
                            name: this.name,
                            class: this.class,
                            navs: navs,
                        });
                    });

                    $('#pageeditor-tools').html(Template('tpl_pageeditor_tools', data));
                },

                // 渲染属性选项卡
                propertyTab: function () {

                    if (Pageeditor.data.selected == 'page') {
                        var html = Template("tpl_edit_pageeditor_page", Pageeditor.data);
                        $("#diy-editor .inner").html(html);
                        var top = 180;
                    } else {
                        var item = $.extend(true, {}, Pageeditor.data.items[Pageeditor.data.selected]);
                        item.itemid = Pageeditor.data.selected;
                        item.merch = Pageeditor.data.merch;
                        item.plugins = Pageeditor.data.plugins;
                        var html = Template("tpl_edit_" + item.id, item);
                        $("#diy-editor .inner").html(html);
                        var top = $(".selected").position().top + 100;
                    }
                    $("#diy-editor").attr("data-editid", Pageeditor.data.selected).show();
                    if (!html) {
                        $("#diy-editor").hide();
                    } else {
                        $("#diy-editor").unbind('animate').animate({"margin-top": top - 130 + "px"});
                        $("#diy-editor").show();
                    }
                    var sliderlength = $("#diy-editor .slider").length;
                    if (sliderlength > 0) {
                        $("#diy-editor .slider").each(function () {
                            var decimal = $(this).data('decimal');
                            var multiply = $(this).data('multiply');
                            var defaultValue = $(this).data("value");
                            if (decimal) {
                                defaultValue = defaultValue * decimal;
                            }
                            $(this).slider({
                                slide: function (event, ui) {
                                    var sliderValue = ui.value;
                                    if (decimal) {
                                        sliderValue = sliderValue / decimal;
                                    }
                                    $(this).siblings(".input").val(sliderValue).trigger("propertychange");
                                    $(this).siblings(".count").find("span").text(sliderValue)
                                }, value: defaultValue, min: $(this).data("min"), max: $(this).data("max")
                            })
                        })
                    }

                    $('#form-items').sortable({
                        opacity: 0.8,
                        placeholder: "highlight",
                        items: '.item',
                        revert: 100,
                        scroll: false,
                        start: function (event, ui) {
                            var height = ui.item.height();
                            $(".highlight").css({"height": height + "px"});
                            $(".highlight").html('<div><i class="fa fa-plus"></i> 放置此处</div>');
                            $(".highlight div").css({"line-height": height - 4 + "px"})
                        },
                        stop: function (event, ui) {
                            Pageeditor.api.render.items();
                            $(document).find(".drag[data-itemid='" + Pageeditor.data.selected + "']").trigger('mousedown');
                        },
                        update: function (event, ui) {
                            var items = {};
                            $(this).find('.item').each(function () {
                                items[$(this).data('id')] = Pageeditor.data.items[Pageeditor.data.selected].data[$(this).data('id')];
                            });
                            Pageeditor.data.items[Pageeditor.data.selected].data = items;
                        }
                    });
                    $("#form-items").disableSelection();
                },

                // 渲染元素
                items: function () {
                    var phone = $("#phone");
                    phone.empty();
                    $.each(Pageeditor.data.items, function (itemid, item) {
                        if (typeof(item.id) !== 'undefined') {
                            var data = $.extend(true, {}, item);
                            data.itemid = itemid;
                            $("#phone").append(Template("tpl_show_" + item.id, data));
                        }
                    });
                    var btnhtml = $("#edit-del").html();
                    $("#phone .drag").append(btnhtml);

                    $("#phone").sortable({
                        opacity: 0.8,
                        placeholder: "highlight",
                        items: '.drag:not(.fixed)',
                        revert: 100,
                        scroll: false,
                        start: function (event, ui) {
                            var height = ui.item.height();
                            $(".highlight").css({"height": height + "px"});
                            $(".highlight").html('<div><i class="fa fa-plus"></i> 放置此处</div>');
                            $(".highlight div").css({"line-height": height - 4 + "px"})
                        },
                        stop: function (event, ui) {
                            Pageeditor.api.render.items();
                            $(document).find(".drag[data-itemid='" + Pageeditor.data.selected + "']").trigger('mousedown');
                        },
                        update: function (event, ui) {
                            var items = {};
                            $(this).find('.drag').each(function () {
                                items[$(this).data('itemid')] = Pageeditor.data.items[$(this).data('itemid')];
                            });
                            Pageeditor.data.items = items;
                        }
                    });
                },

            },

            preview: function (selector, data) {
                $('body').css('background', data.page.background);
                $('title').html(data.page.title);
                var html = '';
                $.each(data.items, function (itemid, item) {
                    if (typeof(item.id) !== 'undefined') {
                        var data = $.extend(true, {}, item);
                        data.itemid = itemid;
                        html += Template("tpl_show_" + item.id, data);
                    }
                });
                $(selector).html(html);
                var swiper = [];
                $('.swiper-container').each(function (a, b) {
                    var options = {
                        pagination: {
                            clickable: true,
                            renderBullet: function (index, className) {
                                console.log(index, className);
                                return '<span class="' + className + '" style="' + this.pagination.$el.data('bullet-style') + '"></span>';
                            }
                        },
                    };
                    swiper[a] = new Swiper('#' + $(this).attr('id'), $.extend(true, {}, options, $(this).data('swiper')));
                });
            }
        },
    };

    return Pageeditor;
});